package com.jc.camerascan.activity.mine;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alipay.sdk.app.PayTask;
import com.jc.camerascan.R;
import com.jc.camerascan.adapter.mine.PricesetAdapter;
import com.jc.camerascan.core.BaseActivity;
import com.jc.camerascan.core.http.bean.CustomApiResult;
import com.jc.camerascan.core.http.callback.TipCallBack;
import com.jc.camerascan.entity.AlipayIndexBean;
import com.jc.camerascan.entity.GetProductListResult;
import com.jc.camerascan.entity.PayIndexBean;
import com.jc.camerascan.entity.event.ALIPaySuccessEvent;
import com.jc.camerascan.entity.event.AliPayEvent;
import com.jc.camerascan.entity.event.PriceSelectEvent;
import com.jc.camerascan.entity.event.WXPaySuccessEvent;
import com.jc.camerascan.entity.event.WechatPayEvent;
import com.jc.camerascan.entity.mine.WeChatPayBean;
import com.jc.camerascan.entity.mine.WechatPayRequests;
import com.jc.camerascan.utils.MMKVUtils;
import com.jc.camerascan.utils.XToastUtils;
import com.jc.camerascan.widget.SpaceItemDecoration;
import com.jc.camerascan.widget.mine.BottomPayTypeDialog;
import com.jc.camerascan.wxapi.WxConstants;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.dialog.LoadingDialog;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xutil.data.DateUtils;
import com.xuexiang.xutil.net.JsonUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @ProjectName: PhotoRecognition
 * @Package: com.jc.camerascan.activity.mine
 * @ClassName: UserCenterActivity
 * @Description: java类作用描述
 * @Author: XuChi
 * @CreateDate: 2020/7/31 11:50
 * @Version: 1.0
 */
public class UserCenterActivity extends BaseActivity {

    @BindView(R.id.titlebar)
    TitleBar titlebar;
    @BindView(R.id.price_title)
    TextView priceTitle;
    @BindView(R.id.price_recyleview)
    RecyclerView priceRecyleview;
    @BindView(R.id.btn_pay)
    SuperButton btnPay;

    private PricesetAdapter rlAdapter;

    private BottomPayTypeDialog payTypeDialog;

    private List<GetProductListResult> data = new ArrayList<>();

    private LoadingDialog mLoadingDialog;

    private PayIndexBean payIndexBean;

    private IWXAPI mWxApi;

    public static void start(Context context) {
        Intent intent = new Intent(context, UserCenterActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_user_center;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        EventBus.getDefault().register(this);
        mWxApi = WXAPIFactory.createWXAPI(getApplicationContext(),
                WxConstants.WX_APP_ID,
                true);
        mWxApi.registerApp(WxConstants.WX_APP_ID);
        titlebar.setTitle("会员中心");
        titlebar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        priceRecyleview.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        rlAdapter = new PricesetAdapter();
        int space = getResources().getDimensionPixelSize(R.dimen.space_10dp);
        int left = getResources().getDimensionPixelSize(R.dimen.space_10dp);
        priceRecyleview.addItemDecoration(new SpaceItemDecoration(space, left));
        priceRecyleview.setAdapter(rlAdapter);//设置适配器

        getProductList();
    }

    @OnClick(R.id.btn_pay)
    public void onViewClicked() {
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).isSelected()) {
                payTypeDialog = new BottomPayTypeDialog(this, data.get(i).getPrice() + "");
                payTypeDialog.setContentView(LayoutInflater.from(this).inflate(R.layout.bottompaytypedialog, null));
                payTypeDialog.show();
            }
        }
    }

    /**
     * 获取产品列表
     */
    private void getProductList() {
        XHttp.get("/api/WechatPay/GetProductList")
                .execute(new CallBackProxy<CustomApiResult<List<GetProductListResult>>, List<GetProductListResult>>(new TipCallBack<List<GetProductListResult>>() {
                    @Override
                    public void onSuccess(List<GetProductListResult> response) {
                        if (response != null && !response.isEmpty()) {
                            data = response;
                            data.get(data.size() - 1).setSelected(true);
                            rlAdapter.setNewData(response);
                        }
                    }
                }) {
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PriceSelectEvent event) {
        for (GetProductListResult datum : data) {
            datum.setSelected(false);
        }
        data.get(event.getPosition()).setSelected(true);
        rlAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WechatPayEvent event) {
        mLoadingDialog = WidgetUtils.getLoadingDialog(this)
                .setIconScale(0.4F)
                .setLoadingSpeed(8);
        mLoadingDialog.show();
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).isSelected()) {
                synchronizedWechatPayRequests(data.get(i).getProduct_id(), "", Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID), (String) data.get(i).getRemark());
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AliPayEvent event) {
        mLoadingDialog = WidgetUtils.getLoadingDialog(this)
                .setIconScale(0.4F)
                .setLoadingSpeed(8);
        mLoadingDialog.show();
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).isSelected()) {
                synchronizedAliPayRequests(data.get(i).getProduct_id(), "", Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID), (String) data.get(i).getRemark());
            }
        }

    }

    private void synchronizedWechatPayRequests(int productId, String user_phone, String device_id, String remark) {
        WechatPayRequests bean = new WechatPayRequests();
        bean.setProduct_id(productId);
        bean.setUser_phone(user_phone);
        bean.setDevice_id(device_id);
        bean.setRemark(remark);
        XHttp.post("/api/WechatPay/Index")
                .upJson(JsonUtil.toJson(bean))
                .execute(new CallBackProxy<CustomApiResult<PayIndexBean>, PayIndexBean>(new TipCallBack<PayIndexBean>() {
                    @Override
                    public void onSuccess(PayIndexBean response) {
                        mLoadingDialog.dismiss();
                        openWxPay(response);
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        mLoadingDialog.dismiss();
                    }
                }) {
                });
    }

    private void openWxPay(PayIndexBean bean) {
        payIndexBean = bean;
        if (!isWXAppInstalledAndSupported()) {
            XToastUtils.warning("请先安装微信app");
        }
        List<WeChatPayBean> signParams = new ArrayList<>();
        signParams.add(new WeChatPayBean("appid", bean.getAppId()));
        signParams.add(new WeChatPayBean("noncestr", bean.getNonceStr()));
        signParams.add(new WeChatPayBean("package", "Sign=WXPay"));
        signParams.add(new WeChatPayBean("partnerid", bean.getMchId()));
        signParams.add(new WeChatPayBean("prepayid", bean.getPrepay_id()));
        signParams.add(new WeChatPayBean("timestamp", bean.getTimeStamp() + ""));

        PayReq req = new PayReq();
        req.appId = bean.getAppId();
        req.partnerId = bean.getMchId();
        req.prepayId = bean.getPrepay_id();
        req.nonceStr = bean.getNonceStr();
        req.timeStamp = bean.getTimeStamp() + "";
        req.packageValue = "Sign=WXPay";
        req.sign = bean.getPaySign();
        mWxApi.sendReq(req);
    }

    private boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        return msgApi.isWXAppInstalled();
    }

    private void synchronizedAliPayRequests(int productId, String user_phone, String device_id, String remark) {
        WechatPayRequests bean = new WechatPayRequests();
        bean.setProduct_id(productId);
        bean.setUser_phone(user_phone);
        bean.setDevice_id(device_id);
        bean.setRemark(remark);
        XHttp.post("/api/Alipay/Index")
                .upJson(JsonUtil.toJson(bean))
                .execute(new CallBackProxy<CustomApiResult<AlipayIndexBean>, AlipayIndexBean>(new TipCallBack<AlipayIndexBean>() {
                    @Override
                    public void onSuccess(AlipayIndexBean response) {
                        mLoadingDialog.dismiss();
                        if (response != null) {
                            MMKVUtils.put("order_no", response.getOrder_no());
                            Runnable payRunnable = new Runnable() {

                                @Override
                                public void run() {
                                    PayTask payTask = new PayTask(UserCenterActivity.this);
                                    Map<String, String> result = payTask.payV2(response.getContent(), true);
                                    EventBus.getDefault().post(new ALIPaySuccessEvent(result));
                                }
                            };
                            Thread payThread = new Thread(payRunnable);
                            payThread.start();
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        mLoadingDialog.dismiss();
                    }
                }) {
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WXPaySuccessEvent event) {
        XToastUtils.success("支付成功");
        finish();
        DateUtils.string2Millis("",new SimpleDateFormat("yyyy年MM月dd日HH:mm") );
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ALIPaySuccessEvent event) {
        Map<String, String> result = (Map<String, String>) event.getObject();
        String resultStatus = result.get("resultStatus");
        if (TextUtils.equals(resultStatus, "9000")) {
            XToastUtils.success("支付成功");
            finish();
        } else {
            XToastUtils.error("支付失败");
        }
    }

}
